package com.web.controller.common;

import cn.hutool.core.util.IdUtil;
import com.common.apiresult.CommonResult;
import com.common.apiresult.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuxuhuang
 * @date 2023年03月30日 20:06
 */
@RestController
@Slf4j
public class CommonController {
    @GetMapping(value = "common")
    public List<String> commonResult() {
        return Arrays.asList();
    }

    @GetMapping(value = "hello")
    @PreAuthorize(value = "hasAnyRole('guest','dormManagement','schoolManagement')")
    public CommonResult hello() {
        return CommonResult.success(ResultCode.SUCCESS);
    }

    @PostMapping("/file/upload")
    public CommonResult fileUpload(MultipartFile file, HttpServletRequest req) {
        Map<String, Object> result = new HashMap<>();
        // 放在本地项目 目录
        String filePath = "D:\\images\\dorm";
        //服务器目录
        //String filePath=“/home/vue3/images/”;
        File folder = new File(filePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // 生成新的文件名
        String oldName = file.getOriginalFilename();
        String newName = IdUtil.simpleUUID() + oldName.substring(oldName.lastIndexOf("."));
        try {
            // 保存文件到指定路径
            file.transferTo(new File(folder, newName));
            String url = "http://101.132.132.130/images/dormitory/" + newName;
            return CommonResult.success(url);
        } catch (IOException e) {
            return CommonResult.failed(ResultCode.FILEUPLOADFAIL);
        }
    }

}
